package com.uxtc.cloud.component;

import com.uxtc.cloud.domain.SecurityUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.TokenEnhancer;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * JWT内容增强器
 *
 * @author 鱼仔
 * @date 2020/6/19
 */
@Component
@Slf4j
public class JwtTokenEnhancer implements TokenEnhancer {
    @Override
    public OAuth2AccessToken enhance(OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
        Map<String, Object> info = new HashMap<>();
        // 判断是否是客户端模式
        boolean clientOnly = authentication.isClientOnly();
        if (!clientOnly) {
            SecurityUser securityUser = (SecurityUser) authentication.getPrincipal();
            //把用户ID设置到JWT中
            info.put("id", securityUser.getId());
            info.put("client_id", securityUser.getClientId());
        } else {
            info.put("client_id", authentication.getPrincipal());
        }
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(info);
        return accessToken;
    }
}
